#include <bits/stdc++.h>
// 2025/01/21
// tag: 
// Author: Zhang Muen
using namespace std;

class UF
{
public:
    vector<int> parents;
    int cnt;

    UF(int n)
    {
        cnt = n;
        for (int i = 0; i <= n; i++)
            parents.push_back(i);
    };

    int find(int i)
    {
        if (parents[i] != i)
            return parents[i] = find(parents[i]);
        return parents[i];
    }

    void un(int i, int j)
    {
        int ri = find(i), rj = find(j);
        if (ri == rj)
            return;
        parents[ri] = rj;
        cnt--;
    }

    int count()
    {
        return cnt;
    }

    bool connected(int p, int q)
    {
        return find(p) == find(q);
    }
};

unordered_map<string, int> m;
unordered_map<int, string> m2;
int cnt;

signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    UF uf(50000);
    string s, c1, c2;
    cin >> s;
    while (s != "$")
    {
        c1 = s.substr(1, s.size() - 1);
        if (s[0] == '#')
        {
            if (!m.count(c1))
                m[c1] = ++cnt, m2[cnt] = c1;
            while (true)
            {
                cin >> s;
                if (s[0] != '+')
                    break;
                c2 = s.substr(1, s.size() - 1);
                if (!m.count(c2))
                    m[c2] = ++cnt, m2[cnt] = c2;
                uf.un(m[c2], m[c1]);
            }
        }
        if (s[0] == '?'){
            c1 = s.substr(1, s.size() - 1);
            cout << c1 << " " << m2[uf.find(m[c1])] << endl;
            cin >> s;
        }
    }
    return 0;
}